package bll

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"golang.org/x/sync/errgroup"
	"math/rand"
	log "maya-service/collector/logger"
	"maya-service/constant"
	"maya-service/model"
	"maya-service/store/redis"
	"maya-service/utils"
	"maya-service/utils/request"
	"time"
)

func ScanAllUserAiQuestionRank() {
	if time.Now().Unix() > 1743433350+84000 {
		return
	}

	list, err := AiConsult.List(context.Background(), &model.AiConsultListRequest{
		Size:  10000000,
		Index: 1,
	})

	if err != nil {
		log.Info("List AI咨询排行榜插入失败")
		return
	}

	redis.KV.Del(context.Background(), "quanxi:ai_consult")

	for _, item := range list.List {
		if len(item.Content) <= 10 || item.UserId == "" || item.UserId == "0" {
			continue
		}
		// 添加到排行榜中
		err = redis.GetLeaderBoardInstance().AddOrUpdateUserScoreByIncrement(context.Background(), "quanxi:ai_consult", item.UserId, item.Scores, 1)
		if err != nil {
			log.Error("AddOrUpdateUserScore AI咨询排行榜插入失败")
		}
	}

}

func ScanAllUserAnswerRecord() {
	if time.Now().Unix() > 1731925164 {
		return
	}

	list, err := AnswerRecord.List(context.Background(), &model.AnswerRecordListRequest{
		Size:  1000000,
		Index: 1,
	})
	if err != nil {
		return
	}

	userMap := make(map[string]struct{})
	for i := 0; i < len(list.List); i++ {
		userMap[list.List[i].UserId] = struct{}{}
	}

	for k, _ := range userMap {
		ctx := context.WithValue(context.Background(), constant.UserData, &request.UserData{
			UserName:    k,
			WxwebOpenid: "",
			Unionid:     k,
			AvatarUrl:   fmt.Sprintf("avatar_%v", k),
		})
		UserLogin(ctx, k)
	}
}

// UserLogin 用户登录
func UserLogin(ctx context.Context, userId string) {
	defer utils.ExceptionCatch()
	defer func() {
		data, _ := request.GetUserData(ctx)

		log.Info("###### 用户登录 ", zap.Any("userId:", userId), zap.Any("data", utils.ToJsonString(data)))
	}()
	var errGroup errgroup.Group
	errGroup.Go(func() error {
		// 统计用户所有的全息次数，只统计闯关的次数以及总分数得出平均分数
		list, err := AnswerRecord.List(ctx, &model.AnswerRecordListRequest{
			UserId: &userId,
		})

		if err != nil {
			return err
		}

		// 写入reids进行排行
		starCount := 0
		scoreCount := 0
		for i := 0; i < len(list.List); i++ {
			score := getScoreByStar(list.List[i].Star)
			scoreCount += score
			starCount += list.List[i].Star
		}

		if starCount <= 0 {
			return nil
		}

		// 添加到排行榜中
		err = redis.GetLeaderBoardInstance().AddOrUpdateUserScore(ctx, "quanxi:question", userId, 0, starCount*10)
		if err != nil {
			log.ErrorCtx(ctx, "全息排行榜插入失败")
		}
		return nil
	})

	// AI 咨询排行榜
	errGroup.Go(func() error {
		list, err := AiConsult.List(ctx, &model.AiConsultListRequest{
			UserId: &userId,
		})

		if err != nil {
			return nil
		}

		consultCount := 0
		scoreCount := 0
		for i := 0; i < len(list.List); i++ {
			scoreCount += list.List[i].Scores
			consultCount += 1
		}

		if consultCount <= 0 {
			return nil
		}

		// 添加到排行榜中
		err = redis.GetLeaderBoardInstance().AddOrUpdateUserScore(ctx, "quanxi:ai_consult", userId, scoreCount, consultCount)
		if err != nil {
			log.ErrorCtx(ctx, "AI咨询排行榜插入失败")
		}
		return nil
	})

	_ = errGroup.Wait()
	return
}

func getScoreByStar(star int) int {
	switch star {
	case 0:
		return 0
	case 1:
		return rand.Intn(50)
	case 2:
		return RandomIntInRange(50, 70)
	case 3:
		return RandomIntInRange(70, 100)
	}
	return 0
}

func RandomIntInRange(min, max int) int {
	// 确保 min <= max
	if min > max {
		min, max = max, min
	}

	// rand.Intn(max-min+1) 生成 [0, max-min] 之间的随机数
	return rand.Intn(max-min+1) + min
}
